package middleware

import (
	"go-exp/pkg/ctxdata"
	"go-exp/pkg/httpresult"
	"go-exp/pkg/myjwt"
	"go-exp/zero/api/internal/config"
	"net/http"
	"strings"
)

type AuthMiddleware struct {
	Config config.Config
}

func NewAuthMiddleware(c config.Config) *AuthMiddleware {
	return &AuthMiddleware{
		Config: c,
	}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		val := r.Header.Get("Authorization")
		// 开始解析jwt用户信息
		replaced := strings.Replace(val, "Bearer ", "", 1)
		authClaims, err := myjwt.ParseAndValidateToken(replaced, m.Config.Auth.AccessSecret)
		// 解析失败直接报错
		if err != nil {
			httpresult.ParamErrorResult(w, err)
			return
		}
		// 将认证信息存储到新的 context 中
		newCtx := ctxdata.SetAuthClaims(r.Context(), authClaims)
		next(w, r.WithContext(newCtx))
	}
}
